from rest_framework import serializers
from ordering.models import Order
from catalogue.serializers import FoodsSerializer

class OrderIDSerializer(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = (                                                                                                                                                                                                                                                                                                                                                                                                                                                            
            'oid'
        )


# 将从数据库获取的数据序列化为json数据，供前端使用
class OrderSerializer(serializers.ModelSerializer):
    # 获取订单的真实商品信息，因为之前只是存储了商品的主键
    foods = FoodsSerializer()

    # 元数据
    class Meta:
        # 序列化器关联的数据库
        model = Order
        # 需要序列化的字段名
        fields = (
            'foods',
            'oid',
            'count',
            'deliver',
            'address',
            'created'
        )

    # def to_representation(self, instance):
    #     data = super().to_representation(instance)
    #     data["foods"]["price"] * data["count"]
    #     return data
    # 可使用序列化器创建订单条目
    def create(self, data):
        return Order.objects.create(**data)
